package repository

import (
	"gitee.com/fierce_wolf/go-fox-edge-common/commEntityManager"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Differ"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/periodTask"
	"gitee.com/fierce_wolf/go-fox-edge-common/edgeEntity"
)

type repoLocalJarMethodTask struct {
}

func (e *repoLocalJarMethodTask) TaskType() periodTask.TaskType {
	return periodTask.TaskShare
}

func (e *repoLocalJarMethodTask) SchedulePeriod() int64 {
	return 10
}

func (e *repoLocalJarMethodTask) Execute() {
	// 将OperateMethodEntity实体同步到OperateEntity实体
	e.syncOperateMethodEntity()

	// 同步本地仓库信息
	fileNameMap, err := LocalJarFileCompScanner.ScanRepoCompEntityByJarMethod()
	if err == nil {
		LocalJarFileCompScanner.ScanRepoCompEntity(fileNameMap)
	}

	// 将DeviceObjInfEntity实体同步到DeviceMapperEntity实体
	e.syncDeviceMapperEntity()
}

func (e *repoLocalJarMethodTask) syncOperateMethodEntity() {
	srcOperateMap, err := commEntityManager.GetEntityMap(edgeEntity.Type.OperateMethodEntity.Type())
	if err != nil {
		return
	}

	dstOperateMap, err := commEntityManager.GetEntityMap(edgeEntity.Type.OperateEntity.Type())
	if err != nil {
		return
	}

	addList := make(map[string]interface{})
	delList := make(map[string]interface{})
	eqlList := make(map[string]interface{})
	Differ.Set.DifferByKey(dstOperateMap, srcOperateMap, &addList, &delList, &eqlList)

	// 只新增，不主动删除和修改。因为operate是用户手动维护的
	for key := range addList {
		srcEntity := srcOperateMap[key]
		if srcEntity == nil {
			continue
		}

		dstEntity := edgeEntity.Type.OperateEntity.Instance()
		dstEntity.BindEntity(srcEntity.(*edgeEntity.OperateMethodEntity))

		commEntityManager.InsertEntity(dstEntity)
	}
}

func (e *repoLocalJarMethodTask) syncDeviceMapperEntity() {
	srcOperateMap, err := commEntityManager.GetEntityMap(edgeEntity.Type.DeviceObjInfEntity.Type())
	if err != nil {
		return
	}

	dstOperateMap, err := commEntityManager.GetEntityMap(edgeEntity.Type.DeviceMapperEntity.Type())
	if err != nil {
		return
	}

	addList := make(map[string]interface{})
	delList := make(map[string]interface{})
	eqlList := make(map[string]interface{})
	Differ.Set.DifferByKey(dstOperateMap, srcOperateMap, &addList, &delList, &eqlList)

	// 只新增，不主动删除和修改。因为operate是用户手动维护的
	for key := range addList {
		srcEntity := srcOperateMap[key]
		if srcEntity == nil {
			continue
		}

		dstEntity := edgeEntity.Type.DeviceMapperEntity.Instance()
		dstEntity.BindEntity(srcEntity.(*edgeEntity.DeviceObjInfEntity))

		commEntityManager.InsertEntity(dstEntity)
	}
}
